package com.example.solrdemo.controller;

import com.alibaba.fastjson.JSON;
import com.example.solrdemo.dao.OrdersRepository;
import com.example.solrdemo.entity.Orders;
import lombok.AllArgsConstructor;
import org.apache.commons.math3.stat.descriptive.summary.Product;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.Group;
import org.apache.solr.client.solrj.response.GroupCommand;
import org.apache.solr.client.solrj.response.GroupResponse;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.params.GroupParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.solr.core.SolrTemplate;
import org.springframework.data.solr.core.query.*;
import org.springframework.data.solr.core.query.result.GroupEntry;
import org.springframework.data.solr.core.query.result.GroupPage;
import org.springframework.data.solr.core.query.result.GroupResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author benjamin_5
 * @Description group分组查询
 * @date 2023/8/19
 */
@RestController
@RequestMapping("group")
@AllArgsConstructor
public class GroupSearchController {
    private final HttpSolrClient solrClient;

    private final SolrTemplate solrTemplate;

    @GetMapping("sellTopFive")
    public Map<String, Long> sellTopFive() {
        Map<String, Long> result = new HashMap<>();
        // 设置查询条件
        SolrQuery query = new SolrQuery().setQuery("*:*").setRows(100);
        // 设置分组条件
        query.set(GroupParams.GROUP, true)
                .set(GroupParams.GROUP_FIELD, "product_name")
                .set(GroupParams.GROUP_LIMIT, 0);
        try {
            QueryResponse response = solrClient.query("orders",query);
            GroupResponse groupResponse = response.getGroupResponse();

            List<GroupCommand> values = groupResponse.getValues();
            GroupCommand group = values.get(0);
            List<Group> productGroups = group.getValues();
            for (Group productGroup : productGroups) {
                result.put(productGroup.getGroupValue(), productGroup.getResult().getNumFound());
            }
            // 根据数量逆序排序，截取前5
            return result.entrySet().stream()
                    .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                    .limit(5)
                    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
        } catch (SolrServerException | IOException e) {
            e.printStackTrace();
            return result;
        }
    }

    @GetMapping("sellTopFive2")
    public Map<String, Long> sellTopFive2() {
        Map<String, Long> result = new HashMap<>();

        // 设置分组条件
        Field field = new SimpleField("product_name");
        SimpleQuery groupQuery = new SimpleQuery(new SimpleStringCriteria("*:*")).setRows(100);
        GroupOptions groupOptions = new GroupOptions()
                .addGroupByField(field)
                .setLimit(0);
        groupQuery.setGroupOptions(groupOptions);

        try {
            GroupPage<Orders> page = solrTemplate.queryForGroupPage("orders", groupQuery, Orders.class);
            GroupResult<Orders> fieldGroup = page.getGroupResult(field);

            List<GroupEntry<Orders>> content = fieldGroup.getGroupEntries().getContent();
            for (GroupEntry<Orders> ordersGroupEntry : content) {
                result.put(ordersGroupEntry.getGroupValue(), ordersGroupEntry.getResult().getTotalElements());
            }

            // 根据数量逆序排序，截取前5
            return result.entrySet().stream()
                    .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                    .limit(5)
                    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
        }catch (Exception e){
            e.printStackTrace();
            return result;
        }

    }
}
